<template>
  <div class="wraper" v-wechat-title="'博文编辑'">
    <el-row>
      <el-card>
        <div slot="header">
          <el-button
              type="warning"
              @click="handleUpload"
              :disabled="isAuth('sys:blog:upload')"
              icon="el-icon-star-on">
            本地上传
          </el-button>
          <el-button
              :disabled="isAuth('sys:blog:add')"
              icon="el-icon-document-checked"
              @click="confirmDraft('blogForm')">
            保存草稿
          </el-button>
          <el-button type="primary"
                     v-if="blogForm.isRelease !== 0 && $route.query.bId == undefined"
                     :disabled="isAuth('sys:blog:add')"
                     icon="el-icon-s-flag"
                     @click="confirmPage('blogForm')">
            发布文章
          </el-button>
          <el-button type="primary"
                     style="margin-right: 10px"
                     v-if="blogForm.isRelease !== 0 && $route.query.bId != undefined"
                     :disabled="isAuth('sys:blog:add')"
                     icon="el-icon-edit"
                     @click="confirmPage('blogForm')">
            修改文章
          </el-button>

        </div>
        <el-form :model="blogForm" :rules="rules" ref="blogForm" label-width="50px" :inline="true">
          <el-col :span="24" id="col">
            <el-form-item label="标题" prop="title" id="title">
              <el-input v-model="blogForm.title" placeholder="标题"></el-input>
            </el-form-item>
            <el-form-item label="标签">
              <el-select v-model="blogForm.tagIds" value-key="id" multiple placeholder="选择标签" clearable>
                <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="分类">
              <el-select v-model="blogForm.categoryId" placeholder="选择分类" clearable>
                <el-option v-for="category in categories" :key="category.id" :label="category.name"
                           :value="category.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="content" id="mavon" style="width: 100%!important;">
              <mavon-editor ref="mavon"
                            v-model="blogForm.content"
                            :ishljs="true"
                            @imgAdd="imgAdd"
                            @imgDel="imgDel"/>
            </el-form-item>
          </el-col>
        </el-form>
      </el-card>
    </el-row>
    <blog-upload v-if="localUploadVisible" ref="localUpload" @getTransformContent="getTransformContent"></blog-upload>
    <el-backtop target=".wraper" :visibility-height="10"></el-backtop>
  </div>
</template>

<script>
import BlogUpload from "@/views/blog/blog-upload";
import {addBlog, detail, updateBlog} from "@/api/blog";
import {categoryList} from "@/api/category";
import {tagList} from "@/api/tag";
import {upload} from "@/api/ossPicture";

export default {
  name: "blog-add-or-update",
  components: {
    BlogUpload,
  },
  data() {
    return {
      categories: [],
      tags: [],
      selectTags: [],
      blogForm: {
        title: '',
        content: '',
        categoryId: '',
        tagIds: [],
        isRelease: '',
        isTop: 0,
        isComment: 1
      },
      rules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
        ],
        content: [
          {required: true, message: '请输入内容', trigger: 'blur'},
        ],
      },
      hasLeave: false,
      originalInfo: {  //进入页面时的博文信息
        title: '',
        content: '',
        categoryId: '',
        tagIds: [],
      },
      localUploadVisible: false, //文件上传dialog
    };
  },
  methods: {
    imgDel(file) {
      console.log('del', file);
    },
    imgAdd(pos, $file) {
      let formdata = new FormData();
      formdata.append('fileData', $file);
      formdata.append('catalog', 'blog');
      formdata.append('isScale', 0);
      upload(formdata).then(res => {
        this.$refs.mavon.$img2Url(pos, res.data[0]);
      })
    },
    //获取导入文件后的内容
    getTransformContent(val) {
      this.blogForm.content = val.content
      this.blogForm.title = val.title
    },
    //打开导入文件模态框
    handleUpload() {
      this.localUploadVisible = true
      this.$nextTick(() => {
        this.$refs.localUpload.init()
      })
    },
    findBlogInfo(id) {
      detail(id).then(res => {
        if (res.status) {
          const blog = res.data
          this.blogForm = blog
          // this.originalInfo = blog
          this.originalInfo.title = blog.title
          this.originalInfo.content = blog.content
          this.originalInfo.categoryId = blog.categoryId
          this.originalInfo.tagIds = blog.tagIds
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },

    //保存草稿
    confirmDraft(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否保存为草稿', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.blogForm.isRelease = 0
            this.submitForm()
          }).catch(() => {
          });
        } else {
          return false;
        }
      })
    },

    //发布文章
    confirmPage(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('是否发布文章', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.blogForm.isRelease = 1
            this.submitForm()
          }).catch(() => {
          })
        } else {
          return false;
        }
      })
    },


    submitForm() {
      const loading = this.$loading({
        lock: true,
        text: '数据上传中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      const release = this.blogForm.isRelease
      const id = this.blogForm.id
      //选中的分类 和 标签ID
      let categoryId = this.blogForm.categoryId;
      let tagId = this.blogForm.tagIds;
      //所有的标签和分类
      let tags = this.tags;
      let category = this.categories
      //获取分类和标签的名字
      let tagName = tags.filter(item => tagId.includes(item.id)).map(item => item.name);
      let categoryName = category.filter(item => item.id == categoryId).map(item => item.name);
      //标签为数组，分类是字符串
      this.blogForm.tagsName = tagName
      this.blogForm.categoryName = categoryName.join()
      if (id) {
        updateBlog(this.blogForm).then(res => {
          loading.close();
          if (res.status) {
            this.$message.success('修改博文成功!');
          } else {
            this.$message.error("修改失败。。")
          }
        }).then(() => {
          this.hasLeave = true;
          this.$router.push({path: 'blog'});
        }).catch(() => {
          loading.close();
        });
      } else {
        addBlog(this.blogForm).then(res => {
          loading.close();
          if (res.status) {
            if (release === 1) {
              this.$message.success('发布成功!');
            } else {
              this.$message.success('保存草稿成功!')
            }
            this.hasLeave = true;
            this.$router.push({path: 'blog'});
          } else {
            if (release === 1) {
              this.$message.error("发布失败。。")
            } else {
              this.$message.success('保存草稿失败。。')
            }
          }
        }).then(() => {
          this.hasLeave = true;
          this.$router.push({path: 'blog'});
        }).catch(() => {
          loading.close();
        });
      }
    },
    //比较两个数组是否完全相同 true:相同 false:不同
    compare(a, b) {
      if (a && b) {
        if (a.length != b.length) {
          return false;
        }
        a.forEach(item => {
          if (b.indexOf(item) === -1) {
            return false
          }
        })
        return true;
      }
      return true;
    }
  },

  mounted() {
    if (this.$route.query.bId) {
      this.findBlogInfo(this.$route.query.bId)
    }
  },

  //数据未保存，确认是否离开页面
  beforeRouteLeave(to, from, next) {
    if (!this.hasLeave) {    //非提交等操作后的离开
      //判断是添加还是修改
      if (this.$route.query.bId) { //修改
        //判断内容是否与修改前相同，相同则直接next，不相同询问
        let oldInfo = this.originalInfo
        let newInfo = this.blogForm
        const result = this.compare(oldInfo.tagIds, newInfo.tagIds)
        if (oldInfo.title == newInfo.title && oldInfo.content == newInfo.content && oldInfo.categoryId == newInfo.categoryId && result) {
          next()
        } else {
          this.$confirm(`你所做的更改尚未保存！！`, '提示', {
            confirmButtonText: '离开',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            next()
          }).catch(() => {
          });
        }
      } else { //添加
        let item = this.blogForm
        //添加时无内容直接next
        if (item.title == '' && item.content == '' && item.categoryId == '' && item.tagIds == '') {
          next()
        } else {
          //添加时有内容离开询问
          this.$confirm(`你所做的更改尚未保存！！`, '提示', {
            confirmButtonText: '离开',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            next()
          }).catch(() => {
          });
        }
      }
    } else {  //发布离开直接next
      next()
    }
  },
  created() {
    categoryList().then(res => {
      this.categories = res.data
    })
    tagList().then(res => {
      this.tags = res.data
    })
  },
}
</script>

<style scoped>
#mavon /deep/ .el-form-item__content {
  width: 100% !important;
}

@media screen and (max-width: 831px) {
  #col /deep/ .el-form-item label {
    display: none !important;
  }

  #col /deep/ .el-form-item:nth-child(-n + 3) {
    width: 225px;
  }
}

/*@media screen and (max-width: 907px) {*/
/*  #col /deep/ .el-form-item:nth-child(-n + 3)  {*/
/*    width: 170px;*/
/*  }*/
/*}*/
</style>
